<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2018/6/27
 * Time: 16:51
 */

namespace App\Libs\Interfaces;

use App\Libs\Curl;

class BaiduTts
{
    protected $_curl;
    protected $_access_token;
    const AUDIO_URL = 'http://tsn.baidu.com/text2audio';
    const AUTH_URL = 'https://openapi.baidu.com/oauth/2.0/token';

    public function __construct($refresh=false)
    {
        $curl = new Curl();
        $this->_curl = $curl;

        $this->_getAccessToken($refresh);
    }

    /**
     * @param string $amt
     * @param string $per 发音人选择, 0为普通女声，1为普通男生，3为情感合成-度逍遥，4为情感合成-度丫丫，默认为普通女声
     * @param string $spd 语速，取值0-9，默认为5中语速
     * @param string $pit 音调，取值0-9，默认为5中语调
     * @param string $vol 音量，取值0-9，默认为5中音量
     * @param string $cuid
     */
    public function transition($text='', $cuid='1', $per='0', $spd='5', $pit='5', $vol='5')
    {
        if($this->_access_token){
            $params = array(
                'tex' => $text,
                'per' => $per,
                'spd' => $spd,
                'pit' => $pit,
                'vol' => $vol,
                'cuid' => $cuid,
                'tok' => $this->_access_token,
                'lan' => 'zh', //固定参数
                'ctp' => 1, // 固定参数
            );
            return $this->_curl->getExe(self::AUDIO_URL,$params);
        }
        return '';
    }

    protected function _getAccessToken($refresh=false)
    {
        $access_token = \Cache::get('baidu_transition_token');
        if($refresh || !$access_token){
            $baidu_config = config('baidutransition');
            $auth_params = [
                'grant_type' => 'client_credentials',
                'client_id' => $baidu_config['apiKey'],
                'client_secret' => $baidu_config['secretKey'],
            ];
            app('galog')->log(json_encode([
                'data' => $auth_params,
            ]), 'baidutts_request', 'ttsAccessTokenRequest');
            $response = json_decode($this->_curl->getExe(self::AUTH_URL,$auth_params),1);

            app('galog')->log(json_encode([
                'data' => $response,
            ]), 'baidutts_response', 'ttsAccessTokenRespopnse');
            if(!empty($response['access_token'])){
                $access_token = $response['access_token'];
                $expires_in = floor($response['expires_in']/ 60);
                \Cache::put(['baidu_transition_token'=>$access_token],$expires_in-1);
            }
        }

        return $this->_access_token = $access_token;
    }
}